<template>
	<view class="elevator-list">
		<!-- Search Filters -->
		<view class="search-section">
			<view class="search-bar">
				<uni-search-bar v-model="searchParams.building" placeholder="搜索建筑物" @confirm="handleSearch"
					@clear="handleSearch" :radius="4" />
				<uni-data-select v-model="searchParams.status" :localdata="STATUS_OPTIONS" placeholder="电梯状态"
					@change="handleSearch" />
			</view>

			<text class="results-count" v-if="!loading">
				共 {{ elevators.length }} 台电梯
			</text>
		</view>

		<!-- Loading State -->
		<view class="loading-state" v-if="loading">
			<uni-load-more status="loading" />
		</view>

		<!-- Error State -->
		<view class="error-state" v-else-if="error">
			<text>{{ error }}</text>
			<button class="retry-btn" @click="elevatorOptions">重试</button>
		</view>

		<!-- Empty State -->
		<view class="empty-state" v-else-if="elevators.length === 0">
			<image src="/static/empty.png" mode="aspectFit" />
			<text>暂无电梯数据</text>
		</view>

		<!-- Elevator List -->
		<view class="elevator-cards" v-else>
			<uni-card v-for="elevator in elevators" :key="elevator.id" :title="elevator.building"
				:extra="getStatusText(elevator.status)" :note="isMaintenanceNeeded(elevator) ? '需要维护' : ''"
				@click="goToDetail(elevator.id)">
				<!-- Elevator Info -->
				<view class="elevator-info">
					<view class="info-grid">
						<view class="info-item">
							<text class="label">位置</text>
							<text class="value">{{ elevator.location }}</text>
						</view>
						<view class="info-item">
							<text class="label">型号</text>
							<text class="value">{{ elevator.model }}</text>
						</view>
						<view class="info-item">
							<text class="label">厂商</text>
							<text class="value">{{ elevator.manufacturer }}</text>
						</view>
						<view class="info-item">
							<text class="label">安装日期</text>
							<text class="value">{{ formatDate(elevator.installationDate) }}</text>
						</view>
						<view class="info-item">
							<text class="label">下次维护</text>
							<text class="value" :class="{'warning': isMaintenanceNeeded(elevator)}">
								{{ formatDate(elevator.nextMaintenanceDate) }}
							</text>
						</view>
					</view>
				</view>

				<!-- Action Buttons -->
				<template v-slot:actions>
					<view class="actions">
						<button class="action-btn status-action"
							:class="[elevator.status && elevator.status.toLowerCase()]"
							@click.stop="updateStatus(elevator)">
							{{ getStatusActionText(elevator.status) }}
						</button>
						<button class="action-btn edit" @click.stop="goToEdit(elevator.id)">
							编辑
						</button>
						<button class="action-btn delete" @click.stop="handleDelete(elevator)">
							删除
						</button>
					</view>
				</template>
			</uni-card>
		</view>

		<!-- Add Button -->
		<uni-fab :pattern="fabPattern" :content="fabContent" horizontal="right" vertical="bottom"
			@trigger="goToCreate" />
	</view>
</template>

<script>
	import {
		request
	} from '@/utils/request'

	// Constants
	const STATUS_OPTIONS = [{
			value: '',
			text: '全部状态'
		},
		{
			value: 'RUNNING',
			text: '运行中'
		},
		{
			value: 'STOPPED',
			text: '已停止'
		},
		{
			value: 'MAINTENANCE',
			text: '维护中'
		},
		{
			value: 'FAULT',
			text: '故障'
		}
	]

	const STATUS_MAP = {
		RUNNING: {
			text: '运行中',
			action: '停止'
		},
		STOPPED: {
			text: '已停止',
			action: '启动'
		},
		MAINTENANCE: {
			text: '维护中',
			action: '完成维护'
		},
		FAULT: {
			text: '故障',
			action: '修复故障'
		}
	}

	const NEXT_STATUS = {
		RUNNING: 'STOPPED',
		STOPPED: 'RUNNING',
		MAINTENANCE: 'RUNNING',
		FAULT: 'MAINTENANCE'
	}

	export default {
		data() {
			return {
				elevators: [],
				loading: false,
				error: null,
				searchParams: {
					building: '',
					status: ''
				},
				STATUS_OPTIONS,
				fabPattern: {
					color: '#007AFF',
					backgroundColor: '#fff',
					selectedColor: '#007AFF',
					buttonColor: '#007AFF'
				},
				fabContent: [{
					iconPath: '/static/plus.png',
					selectedIconPath: '/static/plus.png',
					text: '新增电梯',
					active: false
				}]
			}
		},

		mounted() {
			this.loadElevators()
		},

		methods: {
			async loadElevators() {
				try {
					const elevators = await request({
						url: '/api/elevators'
					});
					this.elevators = elevators;

					if (elevators) {
						this.elevatorOptions = elevators.map(elevator => ({
							value: elevator.id,
							text: `${elevator.building} - ${elevator.location}`
						}));
					} else {
						console.error('Unexpected response format for elevators:', elevators);
						uni.showToast({
							title: '加载电梯失败',
							icon: 'none'
						});
					}
				} catch (err) {
					console.error('Failed to load elevators:', err);
					uni.showToast({
						title: '加载电梯失败',
						icon: 'none'
					});
				}
			},

			handleSearch() {
				this.loadElevators()
			},

			isMaintenanceNeeded(elevator) {
				if (!elevator.nextMaintenanceDate) return false
				const nextDate = new Date(elevator.nextMaintenanceDate)
				const today = new Date()
				const diffDays = Math.ceil((nextDate - today) / (1000 * 60 * 60 * 24))
				return diffDays <= 7
			},

			getStatusText(status) {
				return STATUS_MAP[status] ? STATUS_MAP[status].text : '未知'
			},

			getStatusActionText(status) {
				return STATUS_MAP[status] ? STATUS_MAP[status].action : '更新状态'
			},

			async updateStatus(elevator) {
				try {
					const newStatus = NEXT_STATUS[elevator.status]
					if (!newStatus) return

					await request({
						url: `/api/elevators/${elevator.id}/status`,
						method: 'PUT',
						data: {
							status: newStatus
						}
					})

					uni.showToast({
						title: '状态更新成功',
						icon: 'success'
					})

					this.loadElevators()
				} catch (err) {
					uni.showToast({
						title: '状态更新失败',
						icon: 'none'
					})
				}
			},

			handleDelete(elevator) {
				uni.showModal({
					title: '确认删除',
					content: `是否确认删除 ${elevator.building} 的电梯？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								await request({
									url: `/api/elevators/${elevator.id}`,
									method: 'DELETE'
								})

								uni.showToast({
									title: '删除成功',
									icon: 'success'
								})

								this.loadElevators()
							} catch (err) {
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								})
							}
						}
					}
				})
			},

			formatDate(date) {
				if (!date) return '-'
				return new Date(date).toLocaleDateString('zh-CN')
			},

			goToDetail(id) {
				uni.navigateTo({
					url: `/pages/elevator/detail/index?id=${id}`
				})
			},

			goToEdit(id) {
				uni.navigateTo({
					url: `/pages/elevator/edit/index?id=${id}`
				})
			},

			goToCreate(e) {
				console.log(e);
				uni.navigateTo({
					url: '/pages/elevator/create/index'
				})
			}
		}
	}
</script>

<style>
	.elevator-list {
		padding: 15px;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.search-section {
		margin-bottom: 20px;
	}

	.search-bar {
		display: flex;
		align-items: center;
		gap: 10px;
		margin-bottom: 10px;
	}

	.results-count {
		font-size: 14px;
		color: #666;
	}

	.elevator-cards {
		display: flex;
		flex-direction: column;
		gap: 15px;
	}

	.elevator-info {
		padding: 10px 0;
	}

	.info-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 12px;
	}

	.info-item {
		display: flex;
		flex-direction: column;
		gap: 4px;
	}

	.label {
		font-size: 12px;
		color: #666;
	}

	.value {
		font-size: 14px;
	}

	.warning {
		color: #ff9900;
	}

	.actions {
		display: flex;
		justify-content: flex-end;
		gap: 10px;
	}

	.action-btn {
		font-size: 14px;
		padding: 6px 16px;
		border-radius: 4px;
		border: none;
		color: #fff;
	}

	.status-action {
		background-color: #007AFF;
	}

	.status-action.running {
		background-color: #4cd964;
	}

	.status-action.stopped {
		background-color: #ff9900;
	}

	.status-action.maintenance {
		background-color: #007AFF;
	}

	.status-action.fault {
		background-color: #ff3b30;
	}

	.edit {
		background-color: #007AFF;
	}

	.delete {
		background-color: #ff3b30;
	}

	.loading-state,
	.error-state,
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 40px 0;
		color: #666;
	}

	.retry-btn {
		margin-top: 15px;
		padding: 6px 16px;
		border-radius: 4px;
		background-color: #007AFF;
		color: #fff;
	}

	.empty-state image {
		width: 200px;
		height: 200px;
		margin-bottom: 15px;
	}
</style>